import collections
class Solution(object):
    def numBusesToDestination(self, routes, source, target):
        if source == target:
            return 0
        d = collections.defaultdict(set)
        for index, route in enumerate(routes):
            for bus_station in route:
                d[bus_station].add(index)
        already_index = set()
        already_station = {source}
        now = {source}
        dist = 0
        while now:
            dist += 1
            next_st = set()
            for node in now:
                for index in d[node]:
                    if index not in already_index:
                        already_index.add(index)
                        route = routes[index]
                        for station in route:
                            if station not in already_station:
                                if station == target:
                                    return dist
                                already_station.add(station)
                                next_st.add(station)
            now = next_st
        return -1

